import React, { forwardRef } from "react";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import Select, { SingleValue } from "react-select";
import { useToast } from "@/hooks/use-toast";

import { useForm } from "react-hook-form";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { passwordStrengthTest } from "@/lib/utils";
import { EmployeeI, RoleI, UserI } from "@/types/system";
import { PasswordInput } from "@/components/custom/password-input";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/custom/button";
import useRequest from "ahooks/lib/useRequest";
import { searchEmployeeList, searchRoleList } from "@/api/system";
import { getVbpDepartmentList } from "@/api/api";

interface PropsI {
  onFormSubmit: (data: Partial<UserI>) => void;
}

const UserForm: React.FC<PropsI> = forwardRef((props: PropsI, ref) => {
  const { onFormSubmit } = props;
  const { toast } = useToast();

  const [submitting, setSubmitting] = React.useState<boolean>(false);
  const [employeeList, setEmployeeList] = React.useState<EmployeeI[]>([]);
  const [roleList, setRoleList] = React.useState<RoleI[]>([]);
  const [departmentList, setDepartmentList] = React.useState<any>([]);

  const { loading: loadingEmployees, run: runSearchEmployees } = useRequest(
    (paramsString: string) => searchEmployeeList(paramsString),
    {
      manual: false,
      defaultParams: [""],
      onSuccess(resp: any, params: any) {
        console.log(resp.data);
        setEmployeeList(resp.data.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取员工列表失败",
        });
      },
    }
  );

  const { loading: loadingRoles, run: runSearchRoles } = useRequest(
    (paramsString: string) => searchRoleList(paramsString),
    {
      manual: false,
      defaultParams: [""],
      onSuccess(resp, params: any) {
        // console.log(params);
        setRoleList(resp.data.data);
      },
      onError(e: any, params: any) {
        console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: `${e.detail}`,
        });
      },
    }
  );

  useRequest((paramsString: string) => getVbpDepartmentList(paramsString), {
    manual: false,
    defaultParams: [""],
    onSuccess(resp: any, params: any) {
      setDepartmentList(
        resp.data.data.map((item: any) => {
          return {
            value: item.name,
            label: item.name,
          };
        })
      );
    },
    onError(e: any, params: any) {
      console.log(e);
    },
  });

  const formSchema = z
    .object({
      id: z.string().optional(),
      // username: z.string().trim().min(3, { message: "用户名至少3个字符" }),
      username: z.any(),
      // password: z.string().trim().min(6, { message: "用户名至少6个字符" }),
      password: z.string().refine(passwordStrengthTest, {
        message: "密码至少8位，并且应包含大小写、数字和特殊字符",
      }),
      passwordAgain: z.string().optional(),
      isActive: z.boolean().optional(),
      depts: z.any(),
      roleIds: z.any().optional(),
      department: z.string().optional(),
      // cellphone: z.string().optional(),
      // email: z.string().optional(),
      // nickname: z.string().optional(),
      fullName: z.string().optional(),
      empCode: z.string().optional(),
      // birthday: z.date().optional(),
      // sex: z.number().optional(),
      // score: z.number().optional(),
      // avatarURL: z.string().optional(),
      // lastLoginAt: z.date().optional(),
      // isSuperuser: z.boolean().optional(),
      // roleUsers: z.any().optional(),
      // roles: z.any().optional(),
      // currentRole: z.any().optional(),
      // resources: z.any().optional(),
      // policies: z.any().optional(),
    })
    .refine((data) => data.password === data.passwordAgain, {
      message: "两次密码必须一致",
      path: ["passwordAgain"],
    });

  const defaultValues = {
    id: undefined,
    username: "",
    password: "",
    passwordAgain: "",
    cellphone: "",
    email: "",
    nickname: "",
    // lastName: "",
    // firstName: "",
    fullName: "",
    department: "",
    birthday: new Date(),
    sex: 0,
    score: 0,
    avatarURL: "",
    lastLoginAt: new Date(),
    isActive: true,
    isSuperuser: false,
    roleUsers: [],
    roles: [],
    currentRole: undefined,
    resources: [],
    // policies: [],
  };

  type FormValuesT = z.infer<typeof formSchema>;

  // 表单部分
  const userForm = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
    mode: "onChange",
  });

  // 将 form 对象赋值给 ref
  React.useImperativeHandle(ref, () => ({
    userForm,
  }));

  const handleSelectInputChange = (input: string) => {
    const selectParams = new URLSearchParams();
    selectParams.set("search", input);
    runSearchEmployees(selectParams.toString());
  };

  return (
    <Form {...userForm}>
      <form
        onSubmit={userForm.handleSubmit(onFormSubmit)}
        className="w-full space-y-8"
      >
        <div className="flex flex-col gap-4">
          <FormField
            control={userForm.control}
            name="id"
            render={({ field }) => (
              <FormItem>
                <FormLabel>ID</FormLabel>
                <FormControl>
                  <Input
                    placeholder="id"
                    {...field}
                    disabled={true}
                    autoComplete="off"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="username"
            render={({ field }) => (
              <FormItem>
                <FormLabel>用户名</FormLabel>
                <FormControl>
                  <Select
                    options={employeeList}
                    // 本地有一层过滤，Lable中必须包含检索字段
                    getOptionLabel={(option: EmployeeI) =>
                      `${option.code} ${option.name} ${option.py} ${option.pinyin} ${option.department}`
                    }
                    getOptionValue={(option: EmployeeI) => option.code}
                    onInputChange={handleSelectInputChange}
                    value={field.value}
                    onChange={(option: SingleValue<EmployeeI>) => {
                      field.onChange(option);
                      if (option) {
                        userForm.setValue("fullName", option.name);
                        userForm.setValue("empCode", option.code);
                      }
                    }}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="empCode"
            render={({ field }) => (
              <FormItem>
                <div className="flex items-center justify-between">
                  <FormLabel>工号</FormLabel>
                </div>
                <FormControl>
                  <Input disabled={true} placeholder="工号" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="fullName"
            render={({ field }) => (
              <FormItem>
                <div className="flex items-center justify-between">
                  <FormLabel>姓名</FormLabel>
                </div>
                <FormControl>
                  <Input disabled={true} placeholder="姓名" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="password"
            render={({ field }) => (
              <FormItem>
                <div className="flex items-center justify-between">
                  <FormLabel>密码</FormLabel>
                </div>
                <FormControl>
                  <PasswordInput
                    placeholder="密码"
                    {...field}
                    // autoComplete="off"无效，只使用new-password能解决Chrome自动填充问题
                    // 但不解决点击密码框展示存的账号列表，蜜罐用于保险
                    autoComplete="new-password"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="passwordAgain"
            render={({ field }) => (
              <FormItem>
                <div className="flex items-center justify-between">
                  <FormLabel>密码确认</FormLabel>
                </div>
                <FormControl>
                  <PasswordInput placeholder="密码确认" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="isActive"
            render={({ field }) => (
              <FormItem>
                <FormLabel>在用标记</FormLabel>
                <FormControl>
                  <Switch
                    className="ml-6"
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="roleIds"
            render={({ field }) => (
              <FormItem>
                <FormLabel>角色权限</FormLabel>
                <Select
                  options={roleList.map((role: RoleI) => {
                    return {
                      value: role.id,
                      label: role.name,
                    };
                  })}
                  isMulti
                  isSearchable
                  value={field.value}
                  onChange={field.onChange}
                />
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={userForm.control}
            name="depts"
            render={({ field }) => (
              <FormItem>
                <FormLabel>授权科室</FormLabel>
                <Select
                  options={departmentList}
                  isMulti
                  isSearchable
                  value={field.value}
                  onChange={field.onChange}
                />
                <FormMessage />
              </FormItem>
            )}
          />
          {/* <FormField
                      control={form.control}
                      name="depts"
                      render={({ field }) => {
                        return (
                          <CustomTable
                            totalCount={departmentList.length}
                            defaultFilterColumn="name"
                            manualFiltering={false}
                            getRowId={(originalRow: any, index: number) => {
                              return originalRow.name;
                            }}
                            columns={deptColumns}
                            synchroniseUrl={false}
                            data={departmentList}
                            // initRowSelection={JSON.parse(field.name)}
                            onSelectionChange={(value: any) => {
                              console.log(value);
                              field.onChange(value);
                            }}
                          ></CustomTable>
                        );
                      }}
                    /> */}
        </div>
        <Button disabled={submitting} className="ml-auto" type="submit">
          提交
        </Button>
      </form>
    </Form>
  );
});

export default UserForm;
